package utils

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/redis"
	"github.com/gin-gonic/gin"
	"github.com/wonderivan/logger"
)

func InitSession(r *gin.Engine, config *RedisConfig) {

	store, err := redis.NewStore(10, "tcp", config.Addr+":"+config.Port, "Qq761090", []byte("secret"))
	if err != nil {
		logger.Error(err.Error())
	}
	r.Use(sessions.Sessions("mysession", store))
	r.GET("/incr", func(c *gin.Context) {
		session := sessions.Default(c)
		var count int
		v := session.Get("count")
		if v == nil {
			count = 0
		} else {
			count = v.(int)
			count++
		}
		session.Set("count", count)
		session.Save()
		c.JSON(200, gin.H{"count": count})
	})
	logger.Info("分布式session初始化完成")
}

// set操作
func SetSess(context *gin.Context, key interface{}, value interface{}) error {
	session := sessions.Default(context)
	if session == nil {
		logger.Error("找不到当前会话")
		return nil
	}

	//fmt.Println(key, "   ", value)
	logger.Info("当前key为: ", key)

	session.Set(key, value)
	//sess := session.Get(key)
	//if sess != nil {
	//	logger.Info("这里能够获取得到sess")
	//}

	return session.Save()
}

// get操作
func GetSess(context *gin.Context, key interface{}) interface{} {
	session := sessions.Default(context)
	if session == nil {
		logger.Error("找不到当前会话")
		return nil
	}
	logger.Info("key:  ", key)

	return session.Get(key)
}
